﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ATM_Pro.Module;
using System.Net;
using System.IO;
using System.Drawing;

namespace ATM_Pro
{
    //遮挡报警包
    public class BlockingOutPacketHandle : IPacketHandler
    {

       public event ImageDataChangeHandle DataChange;

        BlockingOutPacketBean bopb = null;

        public BlockingOutPacketHandle()
        {
            bopb = new BlockingOutPacketBean();
        }

        public BlockingOutPacketBean BlockingOutPacket
        {
            get { return bopb; }
        }

        #region IPacketHandler Members

        public bool CanHandle(byte[] bytes)
        {
            return (IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 8)) == 9);
        }

        public void Handle(byte[] bytes)
        {
            int packetLength = -1;
            int packType = -1;
            int imgLength = -1;
            DateTime caputureTime; 

            packetLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 4));
            
            if (packetLength + 8 == bytes.Length)
            {
                packType = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 8));
                caputureTime = GetLocalTime(IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 12)));
                imgLength =IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 16)) ;

                string warnPath = ImageHandle.GenerateSavePath(DateTime.Now);

                MemoryStream faceData = new MemoryStream(bytes, 20, imgLength);
                Image faceimg = System.Drawing.Image.FromStream(faceData);
                FileStream faceFs = File.OpenWrite(warnPath);
                faceimg.Save(faceFs, System.Drawing.Imaging.ImageFormat.Jpeg);
                faceFs.Close();
                faceData.Close();

                bopb.ExceptImg = bytes;
                bopb.ImgLength = imgLength;
                bopb.Path = warnPath;
                bopb.CaputureTime = caputureTime;
                OnDataChanged(this, new DataChangeEventArgs(this.GetType().Name));
            }
         
            
        }

        #endregion

        protected void OnDataChanged(object sender, DataChangeEventArgs e)
        {
            if (this.DataChange != null)
            {
                DataChange(sender, e);
            }
        }

        protected DateTime GetLocalTime(int second)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(second).ToLocalTime();
        }

    }
}
